import random
import time

import Config
from tools import MoveUtil, YoloV8Util, ActionUtil, FindDoorUtil, CommonUtil, FightingUtil, ImageUtil, WindowUtil


class Fight:
    def __init__(self, map_name, position_grab, model):

        self.position_grab = position_grab

        self.model = model

        # 随机移动次数
        self.move_random_index = 0

        # 技能列表
        self.skill_list = ["a", "s", "d", "f", "g"]

        # 当前技能索引
        self.skill_index = 0

        # 地图
        self.map_name = map_name

        # “再次挑战”尝试次数
        self.game_over_step = 0

        self.tips_img = "images/tips.bmp"

        self.confirm_img = "images/confirm.bmp"

        self.challenge_again_img = "images/challenge_again.bmp"

        self.back_town_img = "images/back_town.bmp"

        self.card_img = "images/card.bmp"

        self.to_repair_img = "images/to_repair_in.bmp"

    def move_random(self, seconds):
        # print(f"随机移动【{random_index}】次")
        self.move_random_index += 1
        # 每随机移动3次，时间加倍
        if self.move_random_index > 2:
            seconds = round(self.move_random_index / 3 * seconds, 1)
        if seconds > 2:
            # 重新初始化
            self.move_random_index = 0
        # 等待移动动作完成
        return MoveUtil.move_random(seconds)

    def fight_main(self):
        while True:
            window_rgb = WindowUtil.grab_screen(self.position_grab)
            data_dic = YoloV8Util.predict(self.model, window_rgb)

            # =======================角色是否被遮挡，需要翻牌================================
            flag, loc = ImageUtil.is_icon_exist(window_rgb, self.card_img, (0, 0))
            # card_locs = YoloV8Util.get_data_all(data_dic, Config.card)
            if flag:
                print(f"==========准备翻牌==========")
                card_locs = [(200, 460), (400, 460), (600, 460), (800, 460)]
                random_index = random.randint(0, len(card_locs) - 1)
                ActionUtil.mouse_left_click(card_locs[random_index])
                time.sleep(5)
                continue

            # 刷新角色的坐标
            role_flag, location = YoloV8Util.get_data_one(data_dic, Config.me, False)
            if role_flag is False:
                print("未找到角色，重新获取")
                self.move_random(0.5)
                time.sleep(0.5)
                continue

            # 当前没有移动和战斗，则寻找敌人
            enemys = YoloV8Util.get_data_all(data_dic, Config.enemy, False)
            pick_ups = YoloV8Util.get_data_all(data_dic, Config.pickup)
            print(f"[enemys]:{len(enemys)}   [pick_ups]:{len(pick_ups)}")

            if len(enemys) == 0 and len(pick_ups) == 0:
                # 没事干，就先通过标记找门
                is_find = FindDoorUtil.go_door_from_mark(self.move_random_index, window_rgb, location,
                                                         "images/marks/" + self.map_name)
                print(f"go_door_from_mark===>>>{is_find}")
                if is_find:
                    self.move_random_index += 1
                    continue

                # 没有敌人，则判断是否开门
                is_open, is_open_loc = FindDoorUtil.is_open(data_dic, Config.direction)
                print(f"是否开门：{is_open} {is_open_loc}")

                if is_open:
                    self.move_random_index = 0
                    self.game_over_step = 0

                    FindDoorUtil.find_door(data_dic, location, Config.direction, Config.door)

                else:

                    # =======================1、角色是否需要修装备=======================
                    # flag, loc = YoloV8Util.get_data_one(data_dic, Config.to_repair)
                    flag, loc = ImageUtil.is_icon_exist(window_rgb, self.to_repair_img, (30, 10))
                    if flag:
                        return True, 0

                    # =======================2、再次挑战================================
                    # window = WindowUtil.grab_screen(self.position_grab)
                    flag, loc = ImageUtil.is_icon_exist(window_rgb, self.challenge_again_img, (60, 15))
                    # flag, loc = YoloV8Util.get_data_one(data_dic, Config.challenge_again)
                    if not flag:
                        self.move_random(0.5)
                        time.sleep(0.5)
                        continue
                    else:
                        self.game_over_step += 1
                        if self.game_over_step > 4:
                            print("*" * 10, "游戏结束，准备切换角色", "*" * 10)
                            flag, loc = ImageUtil.is_icon_exist(window_rgb, self.back_town_img, (30, 10))
                            # flag_back, loc_back = YoloV8Util.get_data_one(data_dic, Config.back_town)
                            if flag:
                                ActionUtil.mouse_left_click(loc)
                                # 切换角色
                                time.sleep(10)
                            return True, 2

                        else:
                            print("*" * 10, "辅助暂停，准备再次挑战 " + str(self.game_over_step), "*" * 10)
                            time.sleep(1)
                            # 点击：再次挑战
                            ActionUtil.mouse_left_click(loc)
                            time.sleep(2)

                            # 如果出现[本次登录期间不再显示]，则先确认
                            window = WindowUtil.grab_screen(self.position_grab)
                            flag, loc = ImageUtil.is_icon_exist(window, self.tips_img, (90, 15))
                            print(f"[tips_img]: {flag} {loc}")
                            if flag:
                                ActionUtil.mouse_left_click((loc[0], loc[1]))
                                time.sleep(2)

                                flag, loc = ImageUtil.is_icon_exist(window, self.confirm_img, (15, 15))
                                print(f"[confirm_img]: {flag} {loc}")
                                if flag:
                                    print("再次挑战！！！")
                                    ActionUtil.mouse_left_click((loc[0], loc[1]))
                                    time.sleep(3)
                            return True, 1

            else:
                # =======================战斗================================
                self.move_random_index = 0
                # 获取最近的坐标
                fight_flag, near_loc = CommonUtil.get_near_type_loc(location, enemys, pick_ups)
                if not fight_flag:
                    # 捡东西
                    MoveUtil.moveTo(location, near_loc)
                else:
                    # 打怪
                    # flag = MoveUtil.is_need_enter(location, near_loc, distance=150)
                    # if not flag:
                        MoveUtil.moveTo(location, near_loc)
                    # else:
                        # 开始战斗！！！
                        if len(self.skill_list) > 0:
                            # 不管有没有移动距离，都开始一套技能
                            # 避免角色和敌人重叠，无需移动的情况
                            fight_finish, self.skill_index = FightingUtil.fighting(self.skill_list, self.skill_index)
